package com.hejun.security.controller;

import com.hejun.security.utills.ValidCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class SecurityController {
    @GetMapping("/index")
    public String index(){
        return "index";
    }

    @GetMapping("/toLogin")
    public String toLogin(){
        return "pages/login";
    }

    @GetMapping("/leve{num1}/{num2}")
    public String level(@PathVariable Integer num1,@PathVariable Integer num2){
        return "pages/level"+num1+"/"+num2;
    }
    @GetMapping("/toLogin/error")
    public String error(HttpServletRequest request, Model model){
        //security框架里存的
        AuthenticationException authenticationException = (AuthenticationException) request.getSession()
                .getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        if (authenticationException instanceof UsernameNotFoundException || authenticationException instanceof BadCredentialsException) {
            model.addAttribute("msg","用户名或密码错误");
        } else if (authenticationException instanceof DisabledException) {
            model.addAttribute("msg","用户已被禁用");
        } else if (authenticationException instanceof LockedException) {
            model.addAttribute("msg","账户被锁定");
        } else if (authenticationException instanceof AccountExpiredException) {
            model.addAttribute("msg","账户过期");
        } else if (authenticationException instanceof CredentialsExpiredException) {
            model.addAttribute("msg","证书过期");
        }
        return "pages/login";
    }

    @GetMapping("/validcode")
    public void getValidPicture(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ValidCode validCode=new ValidCode();
        BufferedImage image=validCode.getImage();
        String validcode=validCode.getValidcode();//获取随机验证码
        System.out.println("validcode:"+validcode);
        HttpSession sessions=request.getSession();
        sessions.setAttribute("validcode",validcode);//随机码存入session
        validCode.output(image,response.getOutputStream());//输出
    }
}
